package com.aiyige.page.edituserinfo;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.model.User;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.InputNumFilter;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.dialog.LoadingDialog;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Response;

@Route(path = ARouterConfig.EditUserNamePage)
public class EditUserNamePage extends AppCompatActivity {

    @BindView(R.id.titleBackBtn)
    ImageView titleBackBtn;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.userNameEt)
    EditText userNameEt;
    @BindView(R.id.clearBtn)
    ImageView clearBtn;
    LoadingDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_edit_user_name);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        loadingDialog = new LoadingDialog(this);
        loadingDialog.setCancelable(false);
        titleTv.setText(R.string.input_user_name);
        userNameEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                clearBtn.setVisibility(s.length() != 0 ? View.VISIBLE : View.INVISIBLE);
            }
        });
        userNameEt.setFilters(new InputFilter[]{new InputNumFilter(14, false)});
    }

    @Override
    protected void onResume() {
        super.onResume();
        userNameEt.setText(AccountUtil.getCurrentUser().getAccount());
        userNameEt.setSelection(userNameEt.getText().length());
    }

    @OnClick({R.id.titleBackBtn, R.id.clearBtn, R.id.confirmBtn})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.clearBtn:
                userNameEt.setText("");
                break;
            case R.id.confirmBtn:
                if (TextUtils.isEmpty(userNameEt.getText().toString().trim())) {
                    ToastX.show(R.string.can_not_empty);
                    return;
                }
                new AsyncTask<String, Object, Object>() {

                    @Override
                    protected void onPreExecute() {
                        loadingDialog.showLoading();
                    }

                    @Override
                    protected Object doInBackground(String... params) {
                        try {
                            String userName = params[0];
                            Response<ResponseBody> response = ApiManager.getService().userCenterUsers(AccountUtil.getCurrentUser().getId(), User.newBuilder()
                                    .account(userName)
                                    .build())
                                    .execute();
                            if (response.code() != ResponseCode.CREATED) {
                                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                            }
                            String json = response.body().string();
                            User tempUser = JSON.parseObject(json, User.class);
                            User user = AccountUtil.getCurrentUser();
                            user.setAccount(tempUser.getAccount());
                            AccountUtil.updateCurrentUser(user);
                            return null;
                        } catch (Exception e) {
                            return e;
                        }
                    }

                    @Override
                    protected void onPostExecute(Object o) {
                        loadingDialog.dismiss();
                        if (o instanceof Exception) {
                            ToastX.show(((Exception) o).getMessage());
                        } else {
                            ToastX.show(R.string.edit_user_name_success);
                            finish();
                        }
                    }
                }.execute(userNameEt.getText().toString().trim());
                break;
            default:
                break;
        }

    }
}
